//
//  WmcEditWatermarkVC+Action.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/6/15.
//

import UIKit

// MARK: - 可配置字段

extension WmcEditWatermarkVC {
    /// 点击属性配置条目
    func didSelectOption(_ indexPath: IndexPath, option: WmcWatermarkOptionModel) {
        switch option.fieldType {
        case .title, // 标题
             .text, // 文字
             .record, // 记工
             .isolation, // 隔离
             .sub_title, // 副标题
             .length:
            didSelectWatermarkEditContent(option, indexPath: indexPath)
        case .time: break // 时间
        case .addr: didSelectWatermarkLocal(option) // 地点
        case .weather: break // 天气
        case .lat: break // 经纬度
        case .remark: didSelectWatermarkRemark(option, indexPath: indexPath) // 备注
        case .brand: didSelectWatermarkBrand(option) // 品牌图
        case .altitude: break // 海拔
        case .azimuth: break // 方位角
        case .decibe: break // 分贝
        case .speed: break // 速度
        case .single: break // 单选
        case .results: break // 钢筋数量
        case .custom: break // 自定义
        case .unknow: break
        }
    }

    /// 修改水印信息
    func changeWatermarkOption(_ index: Int, option: WmcWatermarkOptionModel) {
        guard let watermarkModel = viewModel.watermarkModel else { return }
        let defaultList = viewModel.editListRelay.value.map { $0.fieldType }
        // 如果设置了屏蔽某个字段，则需要转换成屏蔽后的索引
        if let actionList = editWatermarkDelegate?.editAttributeList(.current,
                                                                     watermarkModel: watermarkModel,
                                                                     defaultList: defaultList)
        {
            if defaultList.count != actionList.count { // 被修改
                var offsetIndex = 0 // 偏移0
                for (idx, defaultCase) in defaultList.enumerated() {
                    if !actionList.contains(defaultCase) { // 这个字段被修改了，判断该索引并计算偏移量
                        if idx < index { // 真实索引小于被修改索引
                            offsetIndex += 1 // 实际被修改的条目应向下移动
                        }
                    }
                }
                let relayIndex = index + offsetIndex // 获取真实的坐标
                viewModel.changeField(relayIndex, option: option)
            } else { // 没有修改
                viewModel.changeField(index, option: option)
            }
        } else { // 没有修改
            viewModel.changeField(index, option: option)
        }
    }

    /// 点击水印的品牌图字段
    func didSelectWatermarkBrand(_ model: WmcWatermarkOptionModel) {
        let vm = WmcEditBrandVM()
        // 复制一个模型
        vm.watermarkModel = viewModel.watermarkModel?.copyModel()
        vm.watermarkModel?.optionBrand()?.isOpen = true // 开启品牌图编辑
        vm.watermarkStyleMode = viewModel.watermarkStyleMode // 静态动态渲染模式
        WmcNavigatorManager.push(.editbrand, parms: vm)

        vm.editComplete = { [weak self] wm in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.updateWatermarkModel(wm)
        }
    }

    /// 点击水印的备注字段
    func didSelectWatermarkRemark(_ model: WmcWatermarkOptionModel, indexPath: IndexPath) {
        let vm = WmcRemarkVM()
        vm.remarkText = model.content
        WmcNavigatorManager.push(.remark, parms: vm)
        vm.submitRemarkRelay.subscribe(onNext: { [weak self] remark in
            guard let weakSelf = self else { return }
            let newOption = model
            newOption.content = remark
            newOption.isOpen = !remark.isEmpty
            weakSelf.changeWatermarkOption(indexPath.row, option: newOption)
        }).disposed(by: rx.disposeBag)
    }

    /// 点击水印的地点字段
    func didSelectWatermarkLocal(_ model: WmcWatermarkOptionModel) {
        let vm = WmcSelectAddressVM()
        // 静态则使用静态地址
        if viewModel.watermarkStyleMode.isStatic {
            
            // 组装定位模型
            let locationModel = WmcSelectAddressVM.CustomLocationModel()
            locationModel.location = viewModel.watermarkModel?.staticData.staticLocation
            locationModel.reGeocode = viewModel.watermarkModel?.staticData.staticReGeocode
            locationModel.addressPrefix = viewModel.watermarkModel?.staticData.drawStaticAddress?.addressPrefix
            let newAddressModel = WmcSelectAddressModel()
            if let addressModel = viewModel.watermarkModel?.staticData.drawStaticAddress {
                newAddressModel.addressPrefix = addressModel.addressPrefix
                newAddressModel.poi = addressModel.poi
                newAddressModel.isCommonly = addressModel.isCommonly
                newAddressModel.isSelected = addressModel.isSelected
            }
            locationModel.selectedAddress = newAddressModel
            
            let takePhotoAddressModel = WmcSelectAddressModel()
            if let addressModel = viewModel.watermarkModel?.staticData.staticAddress {
                takePhotoAddressModel.addressPrefix = addressModel.addressPrefix
                takePhotoAddressModel.poi = addressModel.poi
                takePhotoAddressModel.isCommonly = addressModel.isCommonly
                takePhotoAddressModel.isSelected = addressModel.isSelected
            }
            locationModel.takePhotoAddress = takePhotoAddressModel
            
            if let staticPioList = viewModel.watermarkModel?.staticData.staticPioList {
                locationModel.poiList = staticPioList
            }
            if let list = viewModel.watermarkModel?.staticData.staticAddressPrefixList {
                locationModel.addressPrefixList = list
            }
            
            vm.customLocation = locationModel
            
            // 选择自定义地址回调
            vm.selectAddress = { [weak self] model in
                guard let weakSelf = self else { return }
                weakSelf.viewModel.watermarkModel?.staticData.drawStaticAddress = model
                // 更新模型
                if let wmModel = weakSelf.viewModel.watermarkModel {
                    weakSelf.viewModel.updateWatermarkModel(wmModel)
                }
            }
        }
        WmcNavigatorManager.push(.selectAddress, parms: vm)
    }

    /// 点击水印的字段编辑内容
    func didSelectWatermarkEditContent(_ model: WmcWatermarkOptionModel, indexPath: IndexPath) {
        // 必须要有一个能编辑
        guard model.enableEditTitle || model.enableEditContent else { return }
        // 隐藏右上角按钮组
        starkView.isHidden = true
        // 配置信息
        editFieldContentView.configModel(model)
        editFieldContentView.indexPath = indexPath
        // 准备弹出
        var config: WmcPresentVC.Config = .init(style: .notice(), contentView: editFieldContentView, contentLayoutBlock: { [weak self] make in
            guard let weakSelf = self else { return }
            make.top.equalTo(weakSelf.navView.snp.bottom)
            make.left.right.equalToSuperview()
            var height = 70
            if model.enableEditTitle {
                height += 95
            }
            if model.enableEditContent {
                height += 180
            }
            make.height.equalTo(height.wmc_autoVer)
        })
        config.hollowRects = [.init(rect: navView.frame)]
        editFieldContentView.show(config: config) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.editFieldContentView.setFirstResponder() // 弹出键盘
        }
        editFieldContentView.willDismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 展示右上角按钮组
            weakSelf.starkView.isHidden = false
        }
    }
}

// MARK: - 默认字段

extension WmcEditWatermarkVC {
    /// 点击水印透明度
    func didSelectWatermarkAlpha(_ model: WmcEditWatermarkSettingCell.Model) {
        let sizeView = WmcSliderAlertView(values: [
            .init(title: "100%", progress: 1),
//            .init(title: "75%", progress: 0.75),
            .init(title: "50%", progress: 0.5),
//            .init(title: "25%", progress: 0.25),
            .init(title: "0%", progress: 0),
        ], isScrollToStep: false)
        sizeView.title = "水印透明度"
        sizeView.submitBtn.isHidden = true
        sizeView.setProgress(CGFloat(model.value.alpha) / 100)
        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: sizeView, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(Wmc_safeAreaBottom + 250)
        }))
        presentVC.show()

        sizeView.progressChangeBlock = { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.changeAlpha(Int(value * 100))
        }

        sizeView.titleView.leftBtn.yp.addEvent { [weak presentVC] _ in
            guard let weakPresentVC = presentVC else { return }
            weakPresentVC.dismissVC()
        }
    }

    /// 点击水印大小
    func didSelectWatermarkSize(_ model: WmcEditWatermarkSettingCell.Model) {
        var sizeList: [WmcSliderView.Model] = []
        WmcWatermarkDetailModel.Size.allCases.forEach { size in
            sizeList.append(.init(title: size.info.title, progress: size.info.progress))
        }
        let sizeView = WmcSliderAlertView(values: sizeList, isScrollToStep: true)
        sizeView.title = "水印大小"
        sizeView.submitBtn.isHidden = true
        sizeView.progressLabel.isHidden = true
        sizeView.setProgress(CGFloat(model.value.size) / 100)
        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: sizeView, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(Wmc_safeAreaBottom + 250)
        }))
        presentVC.show()

        sizeView.progressChangeBlock = { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.changeSize(Int(value * 100))
        }

        sizeView.titleView.leftBtn.yp.addEvent { [weak presentVC] _ in
            guard let weakPresentVC = presentVC else { return }
            weakPresentVC.dismissVC()
        }
    }
}
